package com.example.oj.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.oj.Util.CheckRole;
import com.example.oj.common.Result;
import com.example.oj.entity.Problem;
import com.example.oj.entity.ProblemData;
import com.example.oj.service.ProblemDataService;
import com.example.oj.service.ProblemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/problem")
public class ProblemController {

    @Autowired
    private ProblemService problemService;
    @Autowired
    private ProblemDataService problemDataService;

    @GetMapping("/detail")
    public Result<?> getProblem(@RequestParam(value = "id") Integer id){
        Problem problem = problemService.getById(id);
        return Result.success(problem);
    }

    @PostMapping("/add")
    public Result<?> add(@RequestBody Problem problem){
        String jwt = problem.getJwt();
        Result<?> result = CheckRole.check(jwt);
        if(!result.getCode().equals("0")) return result;
        problemService.save(problem);
        ProblemData problemData = new ProblemData();
        problemData.setId(problem.getId());
        problemData.setTitle(problem.getTitle());
        problemData.setTags(problem.getTags());
        problemData.setCreateDate(new Date());
        problemDataService.save(problemData);
        return Result.success();
    }
    @PostMapping("/update")
    public Result<?> update(@RequestBody Problem problem){
        String jwt = problem.getJwt();
        Result<?> result = CheckRole.check(jwt);
        if(!result.getCode().equals("0")) return result;
        problemService.updateById(problem);
        ProblemData problemData = new ProblemData();
        problemData.setId(problem.getId());
        problemData.setTitle(problem.getTitle());
        problemData.setTags(problem.getTags());
        problemData.setCreateDate(new Date());
        problemDataService.updateById(problemData);
        return Result.success();
    }

    @DeleteMapping("/delete")
    public Result<?> delete(@RequestBody ProblemData problemData) {
        String jwt = problemData.getJwt();
        Result<?> result = CheckRole.check(jwt);
        if (!result.getCode().equals("0")) return result;
        Integer id = problemData.getId();
        problemDataService.removeById(id);
        problemService.removeById(id);
        return Result.success();
    }

}
